<?php

namespace Theme;

use W3\Widget;
use W3\Plugin;

/**
 * 风格列表组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Rows extends Widget
{
    /**
     * @return array
     */
    protected function getThemes()
    {
        return glob(W3_TEMPLATE_DIR . '*', GLOB_ONLYDIR);
    }

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        $themes = $this->getThemes();

        if ($themes) {
            $activated  = 0;
            $result = [];

            foreach ($themes as $key => $theme) 
			{
                $themeFile = $theme . '/index.php';
                if (file_exists($themeFile)) {

                    $info = Plugin::getInfo($themeFile);
                    $info['name'] = basename($theme);

                    if ($info['activated'] = ($this->config->theme == $info['name'])) {
                        $activated = $key;
                    }

                    $screen = array_filter(glob($theme . '/*'), function ($path) {
                        return preg_match("/screenshot\.(jpg|png|gif|bmp|jpeg)$/i", $path);
                    });

                    if ($screen) {
                        $info['screen'] = $this->config->templateUrl . $info['name'] . '/' . basename(current($screen));
                    } else {
                        $info['screen'] = $this->config->assetUrl . 'images/noscreen.png';
                    }

                    $result[$key] = $info;
                }
            }

            $clone = $result[$activated];
            unset($result[$activated]);
            array_unshift($result, $clone);
            array_filter($result, [$this, 'push']);
        }
    }
}
